﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing.Drawing2D;

namespace WChat {
    public partial class MyTabContral : TabControl {
        Image backImage;
        private Timer flashTime = new Timer();//控制标签页闪烁的时间控件     
        Dictionary<string, string> TipTextDictionary = new Dictionary<string, string>();
        private bool _drawTipText = false;
        public MyTabContral() {
            InitializeComponent();
            setStyles();
            backImage = new Bitmap(this.GetType(), "TabButtonBackground.bmp");   // 从资源文件（嵌入到程序集）里读取图片
            this.SizeMode = TabSizeMode.Fixed;  // 大小模式为固定
            this.ItemSize = new Size(44, 44);   // 设定每个标签的尺寸
            flashTime.Interval = 50;//控制呼吸灯效果的时间控件
            flashTime.Enabled = false;
            flashTime.Tick += new EventHandler(tabFlicker_timer_Tick);
        }
        Form parent;
        //int FORM_DELTA = 20;
        //int elapsed = 0;
        //Timer timer;
        //int lastLowerBound = 0;
        //int currentLowerBound = 0;

        public void tabFlicker_timer_Tick(object sender, EventArgs e) {
            base.Invalidate();
        }

        private void setStyles() {
            base.SetStyle(
                 ControlStyles.UserPaint |
                 ControlStyles.OptimizedDoubleBuffer |
                 ControlStyles.AllPaintingInWmPaint |
                 ControlStyles.ResizeRedraw |
                 ControlStyles.SupportsTransparentBackColor,
                 true);
            base.UpdateStyles();
        }
           
        //当被选择
        protected override void OnSelected(TabControlEventArgs e) {
            parent.Text = e.TabPage.Text;
        }
        //当父项目改变
        protected override void OnParentChanged(EventArgs e) {
            if (parent == null)
                parent = this.FindForm();

            parent.Text = this.TabPages[0].Text;
        }

        [Category("外观")]
        [Description("是否绘制标签提示小字")]
        [DefaultValue(typeof(bool), "false")]
        public bool ShowDrawTipText {
            get { return _drawTipText; }
            set {
                _drawTipText = value;
                this.Padding = new Point(this.Padding.X, 4);
            }
        }
        //重绘方法
        protected override void OnPaint(PaintEventArgs e) {

            for (int i = 0; i < this.TabCount; i++) {
               //
                Rectangle bounds = this.GetTabRect(i);
                TabPage page = TabPages[i];
                if (this.SelectedIndex == i) {
                   // e.Graphics.FillRectangle(new SolidBrush(Color.FromArgb(255, 255, 255, 255)), bounds);    //则绘制颜色
                    //e.Graphics.DrawImage(backImage, this.GetTabRect(i));
                }
                if (this.ImageList != null) {
                    int index = this.TabPages[i].ImageIndex;
                    string key = this.TabPages[i].ImageKey;
                    Image icon = new Bitmap(32,32);
                    if (index > -1) {
                        icon = this.ImageList.Images[index];
                    }
                    if (!string.IsNullOrEmpty(key)) {
                        icon = this.ImageList.Images[key];
                    }
                    e.Graphics.DrawImage(icon, bounds.X + (bounds.Width - icon.Width) / 2, bounds.Y + (bounds.Height - icon.Height) / 2);
                }
                //   e.Graphics.DrawRectangle(Pens.Red, this.GetTabRect(i));  //绘制矩形框bounds.X + (bounds.Width - icon.Width) / 2, bounds.Top + this.Padding.Y

                ////以下绘制TipText    
                if (ShowDrawTipText & TipTextDictionary.ContainsKey(page.Name)) {
                    if (TipTextDictionary[page.Name] != null) {
                        string text = TipTextDictionary[page.Name];
                        if (text != "")
                            // DrawTipText(e.Graphics, bounds, text);
                            using (Font f3 = new Font("微软雅黑", 8))  //未读消息条数  小红圆点
                            {
                                e.Graphics.FillEllipse(Brushes.Red, new Rectangle(bounds.X , bounds.Y , 15, 15));
                                e.Graphics.DrawString(text, f3, Brushes.White, new PointF(bounds.X+2 , bounds.Y + 1));
                            }
                    }
                }
              
                //PointF textPoint = new PointF();
                //SizeF textSize = TextRenderer.MeasureText(this.TabPages[i].Text, this.Font);         
                //textPoint.X  = bounds.X + (bounds.Width - textSize.Width) / 2;      // 注意要加上每个标签的左偏移量X  
                //textPoint.Y = bounds.Bottom - textSize.Height - this.Padding.Y;           
                //e.Graphics.DrawString(this.TabPages[i].Text, this.Font,SystemBrushes.ControlLightLight, textPoint.X,textPoint.Y);     // Draw highlights  高光颜色                                                                                                                                    
                //textPoint.Y--;
                //e.Graphics.DrawString(this.TabPages[i].Text, this.Font,SystemBrushes.ControlText,textPoint.X, textPoint.Y);    // 正常颜色   

            }

        }

        private void DrawTipText(Graphics g, Rectangle tabRect, string text) {
            using (Font f3 = new Font("微软雅黑", 8))  //未读消息条数  小红圆点
                {
               // g.FillEllipse(Brushes.Red, new Rectangle(tabRect.X + 10 + 50 - 9, tabRect.Y + 10 - 9, 18, 18));
               // g.DrawString(text, f3, Brushes.White, new PointF(tabRect.X + 10 + 50 - 5, tabRect.Y + 10 - 7));
            
            // MessageBox.Show("kngklj");
            int num = text.Length,fontSize = 8;

                if (Encoding.ASCII.GetString(Encoding.ASCII.GetBytes(text)) != text) {
                fontSize = 6;//判断字符串是否纯字母，存在中文则变字体大小
                num = num + 1;
            }

                 g.FillEllipse(Brushes.Red, new Rectangle(tabRect.X + 10 + 50 - 9, tabRect.Y + 10 - 9, 18, 18));
                 g.DrawString(text, f3, Brushes.White, new PointF(tabRect.X + 10 + 50 - 5, tabRect.Y + 10 - 7));
                Rectangle tipRect = getTipRect(tabRect, num);
                //GraphicsPath tipPath = CreateTipPath(tipRect);
                //using (SolidBrush brush = new SolidBrush(Color.FromArgb(150, Color.Red))) {
                //    g.FillPath(brush, tipPath);
                //}

                // Font f = new System.Drawing.Font(this.Font.FontFamily, fontSize, this.Font.Style);
                // tipRect.Offset(1, -1);
                // TextRenderer.DrawText(g, text, f3, tipRect, Color.White);
               
            }
        }

        protected override void OnSelectedIndexChanged(EventArgs e) {
          //  SelectIndexLog();
            //以下判断语句移除当前选择项的呼吸灯效果和标签显示效果
            if (TabPages.Count > 0 & SelectedTab != null) {
                if (TipTextDictionary.ContainsKey(SelectedTab.Name)) TipTextDictionary.Remove(SelectedTab.Name);
            }
            else if (TabPages.Count <= 0) {        
                TipTextDictionary.Clear();
            }
            base.OnSelectedIndexChanged(e);
        }
    
        /// 将需要显示的Tip文字添加到容器以显示      
        public void TipTextAdd(string tabPageName, string text) {
            flashTime.Enabled = true;
            if (SelectedTab != null) {
                if (SelectedTab.Name == tabPageName)    //不对当前标签添加Tip文字
                { return; }
            }
            if (TabPages.ContainsKey(tabPageName)) {
                if (!TipTextDictionary.ContainsKey(tabPageName)) {
                    TipTextDictionary.Add(tabPageName, text);
                }
                else {
                    TipTextDictionary[tabPageName] = text;
                }
            }
        }
      
        /// 获取Tip绘制矩形框
        private Rectangle getTipRect(Rectangle tabRect, int textLength) {
            if (Alignment == TabAlignment.Top | Alignment == TabAlignment.Bottom) {
                tabRect.Offset(2, 1);
                tabRect.Width++;
            }
            else if (Alignment == TabAlignment.Left) {
                tabRect.Offset(1, 1);
            }
            else if (Alignment == TabAlignment.Right) {
                tabRect.Offset(1, 1);
            }
            tabRect.Height = 10;
            tabRect.Width = 4 + textLength * 7;
            return tabRect;
        }
        /// <summary>
        /// 根据tiprect框体绘制有圆角的框体路径
        /// </summary>
        /// <param name="rect">tiprect</param>
        /// <returns></returns>
        private GraphicsPath CreateTipPath(Rectangle rect) {
            GraphicsPath path = new GraphicsPath();
            path.AddArc(
                rect.X,
                rect.Y,
               rect.Height,
                rect.Height,
                90F,
                180F);
            path.AddLine(
                rect.X + rect.Height / 2,
                rect.Y,
                rect.Right - rect.Height / 2,
                rect.Y);
            path.AddArc(
                rect.Right - rect.Height,
                rect.Y,
                rect.Height,
                rect.Height,
                270F,
                180F);
            path.AddLine(
                rect.X + rect.Height / 2,
                rect.Bottom,
                rect.Right - rect.Height / 2,
                rect.Bottom);

            path.CloseFigure();
            return path;
        }
        /// <summary>
        /// 绘制标签的文字
        /// </summary>
        /// <param name="g">tabcontrol的graphics</param>
        /// <param name="page">标签页tabpage</param>
        /// <param name="tabRect">标签的框体</param>
        /// <param name="hasImage">是否绘制了图片</param>
        private void DrawtabText(
            Graphics g, TabPage page, Rectangle tabRect, bool hasImage) {
            Rectangle textRect = tabRect;
            RectangleF newTextRect;
            StringFormat sf;
            Point padding = this.Padding;
            switch (Alignment) {
            case TabAlignment.Top:
            case TabAlignment.Bottom:
            //if (_haveCloseButton) {
            //    if (hasImage) {
            //        textRect.X = tabRect.X + Radius / 2 + tabRect.Height - padding.X + 6;
            //        textRect.Width = tabRect.Width - Radius - tabRect.Height - 10;
            //    }
            //    else {
            //        textRect.X = tabRect.X + 3 - padding.X;
            //    }
            //}
            //else {
            //    if (hasImage) {
            //        textRect.X = tabRect.X + Radius / 2 + tabRect.Height - 2;
            //        textRect.Width = tabRect.Width - Radius - tabRect.Height;
            //    }
           // }
            TextRenderer.DrawText(
                g,
                page.Text,
                page.Font,
                textRect,
                page.ForeColor);
            break;
            case TabAlignment.Left:
            //if (_haveCloseButton) {
            //    if (hasImage) {
            //        textRect.Height = tabRect.Height - tabRect.Width + padding.X + 5;
            //    }
            //    else {
            //        textRect.Height = tabRect.Height + padding.X + 5;
            //    }
            //}
            //else {
            //    if (hasImage) {
            //        textRect.Height = tabRect.Height - tabRect.Width + 2;
            //    }
            //}
            g.TranslateTransform(textRect.X, textRect.Bottom);
            g.RotateTransform(270F);
            sf = new StringFormat(StringFormatFlags.NoWrap);
            sf.Alignment = StringAlignment.Center;
            sf.LineAlignment = StringAlignment.Center;
            sf.Trimming = StringTrimming.Character;
            newTextRect = textRect;
            newTextRect.X = 0;
            newTextRect.Y = 0;
            newTextRect.Width = textRect.Height;
            newTextRect.Height = textRect.Width;
            using (Brush brush = new SolidBrush(page.ForeColor)) {
                g.DrawString(
                    page.Text,
                    page.Font,
                    brush,
                    newTextRect,
                    sf);
            }
            g.ResetTransform();
            break;
            case TabAlignment.Right:
            //if (_haveCloseButton) {
            //    if (hasImage) {
            //        textRect.Y = tabRect.Y + Radius / 2 + tabRect.Width - padding.X;
            //        textRect.Height = tabRect.Height - Radius - tabRect.Width;
            //    }
            //    else {
            //        textRect.Y = tabRect.Y + Radius / 2 + padding.X - 2;
            //        textRect.Height = tabRect.Height - Radius - tabRect.Width;
            //    }
            //}
            //else {
            //    if (hasImage) {
            //        textRect.Y = tabRect.Y + Radius / 2 + tabRect.Width - 2;
            //        textRect.Height = tabRect.Height - Radius - tabRect.Width;
            //    }
            //}
            g.TranslateTransform(textRect.Right, textRect.Y);
            g.RotateTransform(90F);
            sf = new StringFormat(StringFormatFlags.NoWrap);
            sf.Alignment = StringAlignment.Center;
            sf.LineAlignment = StringAlignment.Center;
            sf.Trimming = StringTrimming.Character;
            newTextRect = textRect;
            newTextRect.X = 0;
            newTextRect.Y = 0;
            newTextRect.Width = textRect.Height;
            newTextRect.Height = textRect.Width;
            using (Brush brush = new SolidBrush(page.ForeColor)) {
                g.DrawString(
                    page.Text,
                    page.Font,
                    brush,
                    newTextRect,
                    sf);
            }
            g.ResetTransform();
            break;
            }
        }

        private void DrawDrawBackgroundAndHeader(Graphics g) {
            int x = 0;
            int y = 0;
            int width = 0;
            int height = 0;
            switch (Alignment) {
            case TabAlignment.Top:
            x = 0;
            y = 0;
            width = ClientRectangle.Width;
            height = ClientRectangle.Height - DisplayRectangle.Height;
            break;
            case TabAlignment.Bottom:
            x = 0;
            y = DisplayRectangle.Height;
            width = ClientRectangle.Width;
            height = ClientRectangle.Height - DisplayRectangle.Height;
            break;
            case TabAlignment.Left:
            x = 0;
            y = 0;
            width = ClientRectangle.Width - DisplayRectangle.Width;
            height = ClientRectangle.Height;
            break;
            case TabAlignment.Right:
            x = DisplayRectangle.Width;
            y = 0;
            width = ClientRectangle.Width - DisplayRectangle.Width;
            height = ClientRectangle.Height;
            break;
            }
            //标签所在的矩形
            Rectangle headerRect = new Rectangle(x, y, width, height);
            Color backColor = Enabled ? Color.White : SystemColors.Control;
            using (SolidBrush brush = new SolidBrush(backColor)) {
                g.FillRectangle(brush, ClientRectangle);
                g.FillRectangle(brush, headerRect);
            }
        }

    }
}
